package com.dyy.AI_System.controller;

import com.dyy.AI_System.domain.po.Users;
import com.dyy.AI_System.domain.po.Departments;
import com.dyy.AI_System.domain.vo.ApiResponse;
import com.dyy.AI_System.service.IUsersService;
import com.dyy.AI_System.service.IDepartmentsService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.time.format.DateTimeFormatter;
import java.util.*;


/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author dyy
 * @since 2025-10-13
 */
@Tag(name = "用户管理", description = "用户相关的CRUD操作API")
@RestController
@RequestMapping("/users")
public class UsersController {

    @Autowired
    private IUsersService usersService;

    @Autowired
    private IDepartmentsService departmentsService;

    private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    /**
     * 获取当前登录用户信息
     */
    @Operation(summary = "获取当前用户信息", description = "获取当前登录用户的详细信息")

    @GetMapping("/me")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getCurrentUser() {
        // 从SecurityContext中获取当前登录用户
        Users currentUser = (Users) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        // 构建用户信息响应对象
        Map<String, Object> userInfo = new HashMap<>();
        userInfo.put("id", currentUser.getId());
        userInfo.put("username", currentUser.getUsername());
        userInfo.put("name", currentUser.getName());
        userInfo.put("email", currentUser.getEmail());

        // 添加部门信息
        if (currentUser.getDepartmentId() != null) {
            Departments department = departmentsService.getById(currentUser.getDepartmentId());
            if (department != null) {
                Map<String, Object> departmentInfo = new HashMap<>();
                departmentInfo.put("id", department.getId());
                departmentInfo.put("name", department.getName());
                userInfo.put("department", departmentInfo);
            }
        }

        userInfo.put("role", currentUser.getRole());
        userInfo.put("avatarUrl", currentUser.getAvatarUrl());
        userInfo.put("phone", currentUser.getPhone());
        userInfo.put("jobTitle", currentUser.getJobTitle());
        userInfo.put("createdAt", currentUser.getCreatedAt() != null ?
                currentUser.getCreatedAt().format(DATE_TIME_FORMATTER) : null);

        return ResponseEntity.ok(ApiResponse.success(userInfo));
    }

    /**
     * 获取所有用户
     */
    @Operation(summary = "获取所有用户", description = "查询系统中所有的用户信息")

    @GetMapping
    public ResponseEntity<ApiResponse<List<Users>>> getAllUsers() {
        List<Users> users = usersService.list();
        return ResponseEntity.ok(ApiResponse.success(users));
    }

    /**
     * 根据ID获取用户
     */
    @Operation(summary = "根据ID获取用户", description = "根据用户ID查询特定用户的详细信息")

    @GetMapping("/{id}")
    public ResponseEntity<ApiResponse<Users>> getUserById(@PathVariable("id") Long id) {
        Users user = usersService.getById(id);
        if (user == null) {
            return ResponseEntity.ok(ApiResponse.fail(404, "未找到该ID对应的用户"));
        }
        return ResponseEntity.ok(ApiResponse.success(user));
    }

    /**
     * 根据用户名获取用户
     */
    @Operation(summary = "根据用户名获取用户", description = "根据用户名查询特定用户的详细信息")

    @GetMapping("/username/{username}")
    public ResponseEntity<ApiResponse<Users>> getUserByUsername(@PathVariable("username") String username) {
        Users user = usersService.getByUsername(username);
        if (user == null) {
            return ResponseEntity.ok(ApiResponse.fail(404, "未找到该用户名对应的用户"));
        }
        return ResponseEntity.ok(ApiResponse.success(user));
    }

    /**
     * 分页查询用户
     */
    @Operation(summary = "分页查询用户", description = "分页查询用户列表，支持关键词搜索和部门、角色筛选")

    @GetMapping("/page")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getUsersByPage(
            @RequestParam(defaultValue = "1",name = "page") Integer pageNum,
            @RequestParam(defaultValue = "10",name = "size") Integer pageSize,
            @RequestParam(required = false,name = "departmentId") Long departmentId,
            @RequestParam(required = false,name = "role") String role,
            @RequestParam(required = false,name = "keyword") String keyword) {

        IPage<Users> page = usersService.pageQuery(pageNum, pageSize, keyword);

        // 构建返回结果对象
        Map<String, Object> result = new HashMap<>();

        // 转换用户列表，只包含需要的字段
        List<Map<String, Object>> userList = new ArrayList<>();
        for (Users user : page.getRecords()) {
            Map<String, Object> userInfo = new HashMap<>();
            userInfo.put("id", user.getId());
            userInfo.put("name", user.getName());
            userInfo.put("email", user.getEmail());

            // 添加部门名称
            if (user.getDepartmentId() != null) {
                String departmentName = departmentsService.getDepartmentNameById(user.getDepartmentId());
                userInfo.put("department", departmentName);
            }

            userInfo.put("role", user.getRole());
            userInfo.put("jobTitle", user.getJobTitle());

            userList.add(userInfo);
        }

        result.put("list", userList);
        result.put("total", page.getTotal());
        result.put("page", pageNum);
        result.put("size", pageSize);

        return ResponseEntity.ok(ApiResponse.success(result));
    }

    /**
     * 根据部门ID获取用户
     */
    @Operation(summary = "根据部门ID获取用户", description = "查询指定部门下的所有激活用户")

    @GetMapping("/department/{departmentId}")
    public ResponseEntity<ApiResponse<List<Users>>> getUsersByDepartmentId(@PathVariable("departmentId") Long departmentId) {
        List<Users> users = usersService.getByDepartmentId(departmentId);
        return ResponseEntity.ok(ApiResponse.success(users));
    }

    /**
     * 创建新用户
     */
    @Operation(summary = "创建新用户", description = "添加一个新的用户到系统中")

    @PostMapping
    public ResponseEntity<ApiResponse<Users>> createUser(@RequestBody Users user) {
        // 确保密码不为空
        if (user.getPassword() == null || user.getPassword().trim().isEmpty()) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body(ApiResponse.fail(400, "密码不能为空"));
        }

        // 默认设置为激活状态
        if (user.getIsActive() == null) {
            user.setIsActive(true);
        }

        boolean saved = usersService.save(user);
        if (saved) {
            return ResponseEntity.status(HttpStatus.CREATED)
                    .body(ApiResponse.success("创建成功", user));
        } else {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ApiResponse.fail(500, "创建失败"));
        }
    }

    /**
     * 更新用户信息
     */
    @Operation(summary = "更新用户信息", description = "更新指定ID用户的详细信息")

    @PutMapping("/{id}")
    public ResponseEntity<ApiResponse<Object>> updateUser(
            @PathVariable("id") Long id,
            @RequestBody Users user) {
        // 检查用户是否存在
        Users existingUser = usersService.getById(id);
        if (existingUser == null) {
            return ResponseEntity.ok(ApiResponse.fail(404, "未找到该ID对应的用户"));
        }

        // 设置ID以确保更新正确的用户
        user.setId(id);

        boolean updated = usersService.updateById(user);
        if (updated) {
            return ResponseEntity.ok(ApiResponse.success("更新成功", null));
        } else {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ApiResponse.fail(500, "更新失败"));
        }
    }

    /**
     * 更新用户状态
     */
    @Operation(summary = "更新用户状态", description = "激活或禁用指定ID的用户")

    @PutMapping("/{id}/status")
    public ResponseEntity<ApiResponse<Object>> updateUserStatus(
            @PathVariable("id") Long id,
            @RequestParam("isActive") Boolean isActive) {
        boolean updated = usersService.updateStatus(id, isActive);

        if (updated) {
            return ResponseEntity.ok(ApiResponse.success("状态更新成功", null));
        } else {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ApiResponse.fail(500, "状态更新失败"));
        }
    }

    /**
     * 删除用户
     */
    @Operation(summary = "删除用户", description = "从系统中删除指定ID的用户")

    @DeleteMapping("/{id}")
    public ResponseEntity<ApiResponse<Object>> deleteUser(@PathVariable("id") Long id) {
        boolean deleted = usersService.removeById(id);
        if (deleted) {
            return ResponseEntity.ok(ApiResponse.success("删除成功", null));
        } else {
            return ResponseEntity.ok(ApiResponse.fail(404, "未找到该ID对应的用户，删除失败"));
        }
    }

    /**
     * 批量删除用户
     */
    @Operation(summary = "批量删除用户", description = "从系统中批量删除多个用户")

    @DeleteMapping("/batch")
    public ResponseEntity<ApiResponse<Object>> batchDeleteUsers(@RequestBody List<Long> ids) {
        boolean deleted = usersService.removeByIds(ids);

        if (deleted) {
            return ResponseEntity.ok(ApiResponse.success("批量删除成功", null));
        } else {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ApiResponse.fail(500, "批量删除失败"));
        }
    }

    /**
     * 更新用户个人资料
     */
    @Operation(summary = "更新用户个人资料", description = "用户更新自己的个人信息")

    @PutMapping("/profile")
    public ResponseEntity<ApiResponse<Object>> updateUserProfile(@RequestBody Map<String, Object> profileData) {
        // 获取当前登录用户
        Users currentUser = (Users) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        // 创建用户对象并设置要更新的字段
        Users userToUpdate = new Users();
        userToUpdate.setId(currentUser.getId());

        // 更新名称
        if (profileData.containsKey("name")) {
            userToUpdate.setName((String) profileData.get("name"));
        }

        // 更新手机号
        if (profileData.containsKey("phone")) {
            userToUpdate.setPhone((String) profileData.get("phone"));
        }

        // 更新职位
        if (profileData.containsKey("jobTitle")) {
            userToUpdate.setJobTitle((String) profileData.get("jobTitle"));
        }

        boolean updated = usersService.updateById(userToUpdate);

        if (updated) {
            return ResponseEntity.ok(ApiResponse.success("更新成功", null));
        } else {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ApiResponse.fail(500, "更新失败"));
        }
    }
}